package com.swfgui.queue
{
	import com.swfgui.interfaces.IDisposable;
	import com.swfgui.utils.time.STimer;
	
	import flash.events.EventDispatcher;

	public class WaitForMethod extends EventDispatcher implements IDisposable
	{
		private var onMethodTrue:Function;
		private var onMethodTrueArgs:Array;
		private var method:Function;
		private var methodTimeOut:Number;
		private var timer:STimer;

		public function WaitForMethod()
		{
		}

		public function waitForMethod(method:Function, 
			onMethodTrue:Function = null, 
			onMethodTrueArgs:Array = null, 
			timeOut:Number=0):void
		{
			this.method = method;
			this.onMethodTrue = onMethodTrue;
			this.onMethodTrueArgs = onMethodTrueArgs;
			
			if (method.call())
			{
				onTimeOut();
			}
			else
			{
				this.methodTimeOut = timeOut * 1000;

				//timeOut = 0，无限循环
				timer = new STimer(100, Math.ceil(methodTimeOut / 100), onTick, null, onTimeOut);
				timer.start();
			}
		}

		protected function onTick():void
		{
			if (method.call())
			{
				onTimeOut();
			}
		}

		protected function onTimeOut():void
		{
			if(onMethodTrue != null)
			{
				onMethodTrue.apply(null, onMethodTrueArgs);
			}
			dispatchEvent(new OperationEvent(OperationEvent.COMPLETE));
			dispose();
		}
		
		public function dispose():void
		{
			if (hasDisposed)
			{
				return;
			}
			_hasDisposed = true;
			this.method = null;
			this.onMethodTrue = null;
			this.onMethodTrueArgs = null;
			if (timer)
			{
				timer.dispose();
			}
		}

		private var _hasDisposed:Boolean;

		public function get hasDisposed():Boolean
		{
			return _hasDisposed;
		}
	}
}